<template>
  <div class="treelist-management-container">
    <slot name="search">这是查询内容</slot>

    <vxe-table
      ref="xTable"
      v-loading="treeListLoading"
      :checkbox-config="{ checkStrictly: checkStrictly }"
      :column-config="{ resizable: true }"
      :data="tableData"
      :height="maxHeight"
      :row-config="{ keyField: 'id' }"
      :scroll-y="{ gt: 20 }"
      show-overflow
      :tree-config="{
        rowField: 'id',
        parentField: 'parentid',
        transform: true,
        expandRowKeys: expandRowKeys
      }"
      @cell-click="handleCellClick"
      @cell-dblclick="handleCellDbClick"
      @checkbox-change="handleCheckboxChange"
    >
      <vxe-column type="checkbox" width="60" />
      <vxe-column field="id" title="序号" tree-node type="seq" width="200" />
      <vxe-column
        v-for="item in treeColumnList"
        :key="item.value"
        :align="item.align || left"
        :field="item.value"
        :title="item.label"
        :width="item.width"
      />

      <slot name="opreration">
        <vxe-column align="center" title="操作" width="250">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="handleAdd(row)"> 添加 </el-button>
            <el-button size="small" type="primary" @click="handleEdit(row)"> 编辑 </el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)"> 删除 </el-button>
          </template>
        </vxe-column>
      </slot>
    </vxe-table>
  </div>
</template>

<script>
import { postRequest } from "@/api/mains";
import { operateType } from "@/plugins/commonType.enum";
import { failMsg, succMsg } from "@/utils/MessageUtils";

export default {
  name: "CommonTreeList",
  components: {},
  props: {
    tableoption: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  emits: { "update:selection-values": null, "handle-edit-info": null },
  setup(props, { emit }) {
    const $baseConfirm = inject("$baseConfirm");
    const $baseMessage = inject("$baseMessage");

    const treeListLoading = ref(false);

    const xTable = ref();
    const tableData = ref([]);
    let selectRow = ref();
    const expandRowKeys = ref([]);

    const maxHeight = ref(props.tableoption.maxHeight);
    const treeColumnList = ref(props.tableoption.columnList);
    const checkStrictly = ref(props.tableoption.checkStrictly);

    //展开树
    const expandAll = () => {
      xTable.value.setAllTreeExpand(true);
    };
    //折叠树
    const collapseAll = () => {
      xTable.value.setAllTreeExpand(false);
    };

    const handleCellClick = ({ row }) => {
      selectRow = row;
    };

    const handleCellDbClick = ({ row }) => {
      const expandRecords = xTable.value.getTreeExpandRecords();
      let hasExpand = false;
      expandRecords.forEach(record => {
        if (record.id == row.id) {
          hasExpand = true;
          return;
        }
      });
      //xTable.value.isExpandByRow(row)
      if (hasExpand) {
        xTable.value.setTreeExpand(row, false);
      } else {
        xTable.value.setTreeExpand(row, true);
      }
    };

    const handleCheckboxChange = () => {
      const selectRows = getSelectRows();
      emit("update:selection-values", selectRows);
    };

    const fetchData = async form => {
      treeListLoading.value = true;

      const responseData = await postRequest(props.tableoption.url, form);
      tableData.value = responseData.data;

      treeListLoading.value = false;

      tableData.value.forEach(item => {
        if (item.parentid == "root") {
          //默认展开的行
          expandRowKeys.value.push(item.id);
        }
      });
    };

    const handleAdd = row => {
      emit("handle-edit-info", operateType.ADD, row);
    };
    const handleEdit = row => {
      emit("handle-edit-info", operateType.EDIT, row);
    };

    const handleDelete = row => {
      if (row != null && row.id) {
        $baseConfirm("你确定要删除当前项吗", null, async () => {
          treeListLoading.value = true;

          const { success, msg } = await postRequest(`${props.tableoption.delOneUrl}/${row.id}`, {});
          treeListLoading.value = false;
          if (success) {
            succMsg(msg);
            await fetchData(props.tableoption.queryForm);
          } else {
            failMsg(msg);
          }
        });
      } else {
        const selectRows = getSelectRows();
        if (selectRows.length > 0) {
          const ids = selectRows
            .map(item => item.id)
            .join()
            .split(","); //将String类型的数据转换为数组类型
          $baseConfirm("你确定要删除选中项吗", null, async () => {
            treeListLoading.value = true;

            const { success, msg } = await postRequest(props.tableoption.delManyUrl, ids);
            treeListLoading.value = false;
            if (success) {
              succMsg(msg);
              await fetchData(props.tableoption.queryForm);
            } else {
              failMsg(msg);
            }
          });
        } else {
          $baseMessage("未选中任何行", "error", "vab-hey-message-error");
        }
      }
    };

    const getSelectRows = () => {
      const $table = xTable.value;
      const selectRows = $table.getCheckboxRecords(true);
      return selectRows;
    };

    onMounted(() => {
      fetchData(props.tableoption.queryForm);
    });

    return {
      xTable,
      tableData,
      treeListLoading,
      selectRow,
      expandRowKeys,
      expandAll,
      collapseAll,
      maxHeight,
      treeColumnList,
      checkStrictly,
      handleCellClick,
      handleCellDbClick,
      handleCheckboxChange,
      fetchData,
      handleAdd,
      handleEdit,
      handleDelete,
      getSelectRows
    };
  }
};
</script>
